<template>
    <van-swipe :autoplay="3000" lazy-render>
        <van-swipe-item v-for="image in product.thumbs_text" :key="image">
            <van-image
                width="100%"
                height="500"
                fit="cover"
                :src="image"
            />
        </van-swipe-item>
    </van-swipe>


    <div class="detailbox">
        <div class="box">
            <div class="left">
                <span v-if="product.live_price">￥{{ product.live_price }}</span>
                <span :class="product.live_price ? 'product_price' : ''">￥{{ product.price }}</span>
            </div>
            <div class="right">
                <div class="sales">{{ product.buy_count }} 人付款</div>
                <div class="region">{{ product.region_text }}</div>
            </div>
        </div>

        <h4>{{ product.name }}</h4>
    </div>
    
    <div class="allkbox"></div>
    
    <!-- 商品规格 -->
    <div class="info_choice">
        <!-- Sku 商品规格 -->
        <div class="commodity" @click="SkuShow = true">
            <div class="opt">
                <div class="title wanl-gray">选择</div>
                <div class="option">
                    <div class="selected">
                        <div v-if="Object.getOwnPropertyNames(SelectedProp).length === 0">
                            <span>选择</span>
                            <span v-for="(val,index) in props" :key="index">{{ val }}</span>
                        </div>

                        <div v-else>
                            <span>已选择</span>
                            <span v-for="(val,index) in Object.values(SelectedProp)" :key="index">{{ val }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="wanl-gray">
                <img src="/assets/images/go.png" />
            </div>
        </div>
        <!-- 服务 -->
        <div class="commodity" @click="TipShow = true">
            <div class="opt">
                <div class="title wanl-gray">服务</div>
                <div class="option">
                    <div class="selected">
                        <div>
                            <span>7天无理由退款</span>
                            <span>·</span>
                            <span>24小时内发货</span>
                            <span>·</span>
                            <span>假一赔十</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="wanl-gray">
                <img src="/assets/images/go.png" />
            </div>
        </div>
    </div>

    <div class="allkbox"></div>

    <div class="comment" @click="ToCommentList">
        <div class="header">
            <div class="title">宝贝评价（{{ CommentCount }}）</div>
            <div class="rate">
                <div class="rate-text">好评率高达{{ ApplauseRate }}%</div>
                <div class="wanl-gray">
                    <img src="/assets/images/go.png" />
                </div>
            </div>
        </div>
        <div class="comment-list">
            <div class="item" v-for="item in CommentList" :key="item.id">
                <div class="user">
                    <div class="avatar">
                        <img :src="item.business.avatar_text" alt="">
                    </div>
                    <div class="nickname">
                        {{ item.business.nickname }}
                    </div>
                    <div class="rate">
                        <van-rate
                            v-model="item.rate"
                            :size="14"
                            color="#ffd21e"
                            void-icon="star"
                            void-color="#eee"
                            readonly
                        />
                    </div>
                </div>
                <div class="content">
                    {{ item.comment }}
                </div>
            </div>
        </div>
    </div>

    <div class="allkbox"></div>

    <div class="product-info">
        <div class="title-box">
            <div class="line"></div>
            <div class="title">产品详情</div>
        </div>

        <div class="content" v-html="product.content"></div>
    </div>

    <!-- 协议条款 -->
    <van-action-sheet v-model:show="TipShow" title="协议条款">
        <div class="ProductTip">
            一、我们如何使用信息 <br />
            二、我们如何共享信息<br />
            三、我们如何转让信息<br />
            四、我们如何公开披露信息<br />
            五、一般储存期限<br />
            六、我们如何确保您的信息安全<br />
            七、您能做什么<br />
            八、我们如何处理未成年人的个人信息<br />
            九、您的个人信息的存储地点<br />
            十、本隐私权政策不适用的范围<br />
            十一、本隐私权政策如何更新<br />
            十二、联系我们<br />
        </div>
    </van-action-sheet>

    <!-- SKU -->
    <van-sku
        ref="SkuRef"
        v-model="SkuShow"
        :sku="sku"
        :properties="properties"
        :goods="goods"
        :goods-id="product.id"
        @add-cart="OnAddCart"
        @buy-clicked="OnBuy"
        @sku-prop-selected="OnSelectedProp"
    >
        <template #sku-actions="props">
            <div class="van-sku-actions">
                <van-button square size="large" type="warning" @click="props.skuEventBus.emit('sku:addCart')">加入购物车</van-button>

                <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
                <van-button square size="large" type="danger" @click="props.skuEventBus.emit('sku:buy')">立即购买</van-button>
            </div>
        </template>
    </van-sku>

    <div style="height: 50px;"></div>


    <!-- 底部导航栏 -->
    <van-action-bar>
        <van-action-bar-icon icon="chat-o" text="客服" />
        <van-action-bar-icon icon="cart-o" text="购物车" :badge="product.cart_count" @click="ToCart" />
        <van-action-bar-icon icon="star" text="已收藏" color="#ff5000" @click="OnCollection" v-if="product.collection_status === true" />
        <van-action-bar-icon icon="star-o" text="收藏" @click="OnCollection" v-else />
        <van-action-bar-button type="danger" text="立即购买" @click="SkuShow = true" />
    </van-action-bar>
</template>

<script setup>
    /* 
        商品规格组件
        安装指令：npm install vant-sku
    */
    import VanSku from 'vant-sku';
    import 'vant-sku/dist/index.css';

    const { proxy } = getCurrentInstance();

    // 当前登录用户信息
    const business = Object.getOwnPropertyNames(proxy.$business.value).length > 0 ? proxy.$business :  ref({});
    // 商品id
    const proid = ref(proxy.$route.query.proid ?? 0);
    // 商品数据
    const product = ref({});

    // 条款服务
    const TipShow = ref(false);

    // 显示商品规格弹出层
    const SkuShow = ref(false);
    // 商品规格数据
    const sku = ref({});
    // 商品属性数据
    const properties = ref([]);
    // sku里的商品信息
    const goods = ref({});
    const SkuRef = ref({});
    // 该商品的规格名称
    const props = ref(['商品规格']);
    // 选中的属性
    const SelectedProp = ref({});
    // 评价数据
    const CommentList = ref([]);
    // 好评率
    const ApplauseRate = ref(0);
    // 评价总数
    const CommentCount = ref(0);

    onBeforeMount(() =>
    {
        GetProductInfo();
    })

    const GetProductInfo = async () =>
    {
        let params = {
            proid:proid.value
        }        
        
        if(business.value.hasOwnProperty('id'))
        {
            params.busid = business.value.id;
        }

        let result = await proxy.$POST({
            url:'/product/info',
            params
        })

        if(result.code === 1)
        {
            product.value = result.data.product;
            sku.value = result.data.sku;
            properties.value = Object.values(result.data.properties);
            goods.value = {picture: product.value.thumb_text};
            props.value = result.data.props.length > 0 ? result.data.props : ['数量'];
            CommentList.value = result.data.CommentList;

            // 把评分转成整数，因为评分组件绑定值的数据类型是Number
            CommentList.value.map(item =>
            {
                item.rate = parseInt(item.rate);
            })
            
            ApplauseRate.value = result.data.ApplauseRate;
            CommentCount.value = result.data.CommentCount;
        }else
        {
            proxy.$fail({
                message:result.msg,
                onClose:() =>
                {
                    proxy.$router.back();
                }
            })
        }
    }

    const OnAddCart = async (SkuData) =>
    {
        if(!business.value.hasOwnProperty('id') || Object.getOwnPropertyNames(business.value).length === 0)
        {
            proxy.$confirm({
                title:'跳转登录提示',
                message:'是否确认跳转到登录？'
            }).then(() =>
            {
                proxy.$cookies.set('redirect',{query:{proid:proid.value},path:'/product/info'});

                proxy.$router.push('/business/login');
                
            }).catch(() => {});

            return false;
        }

        // 判断是否有选择规格
        if(properties.value.length > 0 && !SkuData.selectedSkuComb)
        {
            proxy.$fail('请选择商品规格');
            return false;
        }

        // 购买数量
        let SelectedNum = SkuData.selectedNum

        if(SelectedNum <= 0)
        {
            proxy.$fail('购买数量不能小于等于0');
            return false;
        }

        // 选择的属性id
        let relationids = [];

        // 有规格
        if(properties.value.length > 0)
        {
            let SkuProps = SkuData.selectedSkuComb.properties;
            
            for(let item of SkuProps)
            {
                let id = item.v[0] ? item.v[0]['id'] : 0;
                if(id) relationids.push(id);
            }
        }

        // 组装数据
        let params = {
            busid: business.value.id,
            proid: proid.value,
            nums: SelectedNum,
            relationids:relationids.join(','), //规格id
        }

        // 发送请求
        let result = await proxy.$POST({
            url: '/cart/add',
            params
        })

        if(result.code === 1)
        {
            SkuShow.value = false;

            product.value.cart_count = result.data;

            proxy.$confirm({
                title:'加入购物车成功',
                message:'是否跳转购物车进行结算？'
            }).then(() =>
            {
                proxy.$router.push({
                    path:'/cart',
                    query:{action:'info'}
                })
            }).catch(() => {});
        }else{
            proxy.$fail(result.msg);
        }
    }

    const OnBuy = async (SkuData) =>
    {
        if(!business.value.hasOwnProperty('id') || Object.getOwnPropertyNames(business.value).length === 0)
        {
            proxy.$confirm({
                title:'跳转登录提示',
                message:'是否确认跳转到登录？'
            }).then(() =>
            {
                proxy.$cookies.set('redirect',{query:{proid:proid.value},path:'/product/info'});

                proxy.$router.push('/business/login');
                
            }).catch(() => {});

            return false;
        }

        // 判断是否有选择规格
        if(properties.value.length > 0 && !SkuData.selectedSkuComb)
        {
            proxy.$fail('请选择商品规格');
            return false;
        }

        // 购买数量
        let SelectedNum = SkuData.selectedNum

        if(SelectedNum <= 0)
        {
            proxy.$fail('购买数量不能小于等于0');
            return false;
        }

        // 选择的属性
        let relations = [];

        // 如果是直播商品就按直播价格购买，否则商品原价
        let price = product.value.live_price ? product.value.live_price : product.value.price;

        // 转浮点数
        let total = parseFloat(price);

        // 判断商品是否属于直播商品
        let type = product.value.live_price ? 'live' : 'product';

        // 有规格
        if(properties.value.length > 0)
        {
            // 选中的属性
            let SkuProps = SkuData.selectedSkuComb.properties;
            
            for(let item of SkuProps)
            {
                // 获取规格
                let prop = item.v[0] ? item.v[0] : {};

                if(prop.id)
                {
                    // 每个规格的加价
                    let PropPrice = (prop.price / 100).toFixed(2);

                    // 计算出所有选中的规格加价后的商品价格
                    total += parseFloat(PropPrice);

                    relations.push({
                        title:item.k ? item.k : '',
                        value:prop.name,
                        price:PropPrice
                    })
                }
            }
        }

        let data = [];

        // 组装数据
        data.push({
            proid: proid.value,
            nums: SelectedNum,
            product:product.value,
            total:(total * SelectedNum).toFixed(2),
            price:total.toFixed(2),
            attrs:relations, // 商品规格
            type
        })

        // 把组装好的数据存入本地存储里
        proxy.$cart.value = data;

        proxy.$router.push('/cart/confirm');
    }

    const OnSelectedProp = ({propValue}) =>
    {
        SelectedProp.value[propValue.skuKeyStr] = propValue.name;
    }

    const OnCollection = async () =>
    {
        // 判断是否登录   
        if(!business.value.hasOwnProperty('id') || Object.getOwnPropertyNames(business.value).length === 0)
        {
            proxy.$confirm({
                title:'跳转登录提示',
                message:'是否确认跳转到登录？'
            }).then(() =>
            {
                proxy.$cookies.set('redirect',{query:{proid:proid.value},path:'/product/info'});

                proxy.$router.push('/business/login');
                
            }).catch(() => {});

            return false;
        }

        let params = {
            busid:business.value.id,
            proid:proid.value
        }

        let result = await proxy.$POST({
            url:'/product/collection',
            params
        })

        if(result.code === 1)
        {
            if(result.data === 'add')
            {
                product.value.collection_status = true;
            }else if(result.data === 'delete')
            {
                product.value.collection_status = false;
            }
        }else
        {
            proxy.$fail(result.msg);
        }
    }

    const ToCommentList = () => proxy.$router.push({path:'/product/comment',query:{proid:proid.value}});

    // 跳转购物车
    const ToCart = () =>
    {
        if(!business.value.hasOwnProperty('id') || Object.getOwnPropertyNames(business.value).length === 0)
        {
            proxy.$confirm({
                title:'跳转登录提示',
                message:'是否确认跳转到登录？'
            }).then(() =>
            {
                proxy.$cookies.set('redirect',{path:'/cart',query:{action:'info'}});

                proxy.$router.push('/business/login');
                
            }).catch(() => {});

            return false;
        }

        proxy.$router.push({path:'/cart',query:{action:'info'}});
    }
</script>

<style scoped>
    @import url('/assets/css/ProductInfo.css');
</style>